<?php

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

namespace App\Services\Impl;

use App\Models\Master;
use App\Services\ICacheService;
use App\Services\ICookieService;
use App\Services\ISessionService;
use App\Common\Constant\SessionKey;
use Illuminate\Support\Str;

/**
 * Description of SessionServiceImpl
 *
 * @author ownfi
 */
class SessionServiceImpl implements ISessionService{

    private $cacheService;
    private $cookieService;

    public function __construct(ICacheService $cacheService,ICookieService $cookieService)
    {
        $this->cacheService = $cacheService;
        $this->cookieService = $cookieService;
    }
    
    public function flash($key, $value = null){
        if ($value === null){
            $value = session($key);
            session()->forget($key);
            return $value;
        }else{
            session()->put($key, $value);
        }
    }

    public function genFlashToken()
    {
        $sessionKey = SessionKey::flashTokenKey();
        $token = Str::random(32);
        session()->flash($sessionKey, $token);
        return session()->has($sessionKey) ? $token : false;
    }

    public function getFlashToken()
    {
        return session(SessionKey::flashTokenKey());
    }

    public function getRedirectUrl($default)
    {
        return $this->flash(SessionKey::redirectUrlKey()) ? : url($default);
    }

    public function setRedirectUrl($redirectUrl)
    {
        return $this->flash(SessionKey::redirectUrlKey(),$redirectUrl);
    }

    public function getRefererUrl($default = null)
    {
        return session(SessionKey::refererUrlKey()) ? : ($default ? url($default) : request()->header('referer'));
    }

    public function setRefererUrl($refererUrl)
    {
        $sessionKey = SessionKey::refererUrlKey();
        session([$sessionKey=>$refererUrl]);
        return session()->has($sessionKey);
    }

}
